package br.usp.pcs.basys.event;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import br.usp.pcs.basys.Job;
import br.usp.pcs.basys.engine.IResources;
import br.usp.pcs.basys.engine.UnavaiableResourceException;

public class MemoryRequest extends ComputerSystemEvent {

	
	public MemoryRequest(Job job, Date date, IResources resources) {
		super(job, date, resources);
	}

	@Override
	List<ActionResult> run() {
		List<ActionResult> result = new ArrayList<ActionResult>();
		Long requiredMemorySpace = job.getRequiredMemorySpace();
		try {
			resources.allocate(requiredMemorySpace);
			result.add(scheduleProcessorRequest());
		} catch (UnavaiableResourceException e) {
			resources.queue(this);
			result.add(new EventQueueResult(this));
		}
		return result;
	}

	private ActionResult scheduleProcessorRequest() {
		Long duration = job.getMeanRelocationTime();
		Date nextEventDate = getDateAfterWaiting(duration);
		ComputerSystemEvent nextEvent = new ProcessorRequest(job,nextEventDate,resources);
		resources.add(nextEvent);
		ActionResult result = new ScheduledEventResult(nextEvent);
		return result;
	}

}
